package com.nulldev.util.web.flexibleKit.flexRenderer.paths.subgens;

import com.nulldev.util.VariableAPI.ArrayUtils;
import com.nulldev.util.graphics.renderIt.api.renderItGraphicsInterface;
import com.nulldev.util.graphics.renderIt.api.core.RITFont;
import com.nulldev.util.graphics.renderIt.renderer.global.rColor;
import com.nulldev.util.graphics.renderIt.util.renderPosition;
import com.nulldev.util.gui.fontAPI.FontManager;
import com.nulldev.util.web.flexibleKit.flexRenderer.FlexEnvironment;
import com.nulldev.util.web.flexibleKit.flexRenderer.paths.PathGenerator;
import com.nulldev.util.web.flexibleKit.flexRenderer.styling.fonts.flexFontManager;
import com.nulldev.util.web.flexibleKit.general.RenderOperation;
import com.nulldev.util.web.flexibleKit.global.GlobalRendererSettings;
import com.nulldev.util.web.flexibleKit.jfvParse.Node;

public class BlockquoteGenerator implements PathGenerator {

	private static final int PADDING = 50;

	@Override
	public RenderOperation generate(final Node n, final PathGenerationFlags... flags) {
		final RenderOperation ri = new RenderOperation() {

			private RITFont font;

			@Override
			public renderPosition doRender(final renderItGraphicsInterface iface, final renderPosition rp, final FlexEnvironment imgCache) {
				final int fontSize = GlobalRendererSettings.SCALE_TEXT_AUTOMATICALLY ? iface.viewport_getWidth() / 32
						: flexFontManager.getFontSize("blockQuote");
				final String s = n.getTextContent();
				if (isBlankLine(s))
					return rp;
				rp.appendGetY(fontSize);
				if (font == null)
					font = iface.awt_make_font(FontManager.gets("Product Sans", "Roboto"));
				rp.appendGetX(PADDING);
				final int inc = iface.text_scalable(s, (iface.viewport_getWidth() - 100 - PADDING), rp.getY(), font.deriveToSize(fontSize), rColor.BLACK);
				rp.addY(inc);
//				i.requestViewportHeight(rp.getY());
//				i.runQuirkFix(RenderingQuirks.RESET_X_AFTER_CALL);
				return rp.clone().addX(s.length() * fontSize);
			}

			@Override
			public Node operationFor() {
				return n;
			}

			@Override
			public boolean keepInline() {
				return ArrayUtils.contains(flags, PathGenerationFlags.RENDER_INLINE);
			}
		};
		return ri;
	}

	public static boolean isBlankLine(final String s) {
		if (s.equalsIgnoreCase("\n") || s.equalsIgnoreCase("\t"))
			return true;
		if (s.startsWith("\\u000a") && s.endsWith("\\u000a"))
			return true;
		if (s.length() < 12) {
			for (final char c : s.toCharArray()) {
				if (!(c == ' '))
					return false;
			}
			return true;
		} else {
			return s.startsWith(" ") && s.endsWith(" ");
		}
	}
}
